#!/bin/bash

P6="/dev/mmcblk0p6"
P1="/dev/mmcblk0p1"
P4="/dev/mmcblk0p4"
APP_PATH="/opt/middleware"
Gold="/home/p1"
ascend_dmi_install_path="/home/data/"

CheckP6Mount=`df -h | awk '{if($1=="/dev/mmcblk0p6"){print $6}}'`
CheckP1Mount=`df -h | awk '{if($1=="/dev/mmcblk0p1"){print $6}}'`
GetHaPkgName=`ls|grep HA |grep tar.gz$ `

HAPkgCmsCrl=""
INSTALL="./install.sh"
BackupHAPath="habackup"
UpgradgeLog="/var/alog/AtlasEdge_log/middleware.log"

declare -i Err_OK=0 
declare -i Err_MkdirAppPathFailed=1
declare -i Err_SpaceNotEnough=2
declare -i Err_CopyPkgToGoldFailed=3
declare -i Err_CopyRollbackToGoldFailed=4
declare -i Err_UnmountGoldFailed=5 
declare -i Err_InputParamInvalid=6
declare -i Err_MountP6Failed=7
declare -i Err_ExportEnvFailed=8
declare -i Err_MountGoldFailed=9
declare -i Err_MkdirGoldFailed=10
declare -i Err_MkEdgeBackupPathFailed=11
declare -i Err_MkHABackupPathFailed=12
declare -i Err_BackupEdgeFailed=13
declare -i Err_BackupHAFailed=14
declare -i Err_UpgradeEdgeFailed=15
declare -i Err_UpgradeHAFailed=16
declare -i Err_MkEdgePkgPathFailed=17
declare -i Err_UnzpiEdgePkgFailed=18
declare -i Err_InstallEdgeFailed=19
declare -i Err_MkdirHomeDataFailed=20
declare -i Err_CpCertKeyFailed=21
declare -i Err_CfgEdgeFailed=22
declare -i Err_UnZipHA1Failed=23
declare -i Err_UnZipHA2Failed=24
declare -i Err_InstallHAFailed=25
declare -i Err_UnzipHAFailed=26
declare -i Err_MkHaHandlerFailed=27
declare -i Err_CpHAConfigFailed=28
declare -i Err_CpEdgeDBFailed=29
declare -i Err_TransEdgeCfgFailed=30
declare -i Err_ContainerExportPyFailed=31
declare -i Err_ConfigExportPyFailed=32
declare -i Err_HandleKeyManagerError=35

declare -i Err_EdgePathAlreadyMount=36
declare -i Err_EdgeNotBackup=37
declare -i Err_CpEdgeBackupFailed=38
declare -i Err_CpHABackupFailed=39
declare -i Err_HaNotBackup=40
declare -i Err_GoldPathAlreadyMount=41
declare -i Err_findNoHAPacket=42
declare -i Err_findNoAtlasEdgePacket=43
declare -i Err_findNoAscendDmiTarPacket=44
declare -i Err_findNoAscendDmiRunPacket=45

_log() 
{
  level=$1
  shift 1
  #echo "$(date ${date_format}) -${MODE_NAME}- ${level}- $*" >> ${UpgradgeLog}
  echo "$(date ${date_format}) -${MODE_NAME}- ${level}- $*"
}

logger_Debug() 
{
  echo "$@"
}

logger_Info() 
{
  _log INFO "$@"
}

logger_Warn() 
{
  _log WARN "${color_yellow}$*${color_norm}"
}

logger_Error() 
{
  _log ERROR "${color_red}$*${color_norm}"
}


function setEnv()
{
  P6_Mount=${CheckP6Mount}
  if [ ${P6_Mount} ]; then
      APP_PATH=${P6_Mount}
  else
      if [ ! -d ${APP_PATH} ];then
          mkdir -p ${APP_PATH}
          ret=$?
          if [ $ret -ne 0 ];then
              echo "mkdir ${APP_PATH} failed:$ret"
              return $Err_MkdirAppPathFailed
          fi  
      else
          return $Err_EdgePathAlreadyMount
      fi

      mount ${P6} ${APP_PATH}
      if [ $? -ne 0 ];then
          return $Err_MountP6Failed
      fi
  fi

  return $Err_OK
}

function rmMiddleware()
{
    if [ -d $APP_PATH/AtlasEdge ];then
        if [ -f $APP_PATH/AtlasEdge/run.sh ];then
          $APP_PATH/AtlasEdge/run.sh uninstall
          if [ -d $APP_PATH/AtlasEdge/ ];then
              rm -r $APP_PATH/AtlasEdge/
          fi
        fi
    fi  

    if [ -d $APP_PATH/ha ];then
        if [ -f $APP_PATH/ha/uninstall.sh ];then
          cd $APP_PATH/ha/
          ./uninstall.sh -q
          cd -
          if [ -d $APP_PATH/ha/ ];then
              rm -r $APP_PATH/ha/
          fi
        fi
    fi

    if [ -d $APP_PATH/$BackupHAPath ];then
        rm -r $APP_PATH/$BackupHAPath
    fi
}

function installAtlasEdge()
{
  EdgePkg="AtlasEdgePkg"
  AtlasEdgeTar=`ls|grep -E "atlasedge|AtlasEdge" |grep tar.gz$ `

  if [[ -z "${AtlasEdgeTar}" ]]; then
    logger_Info "find No AtlasEdgeTar return"
    return $Err_findNoHAPacket
  fi

  mkdir -p ${APP_PATH}/${EdgePkg}
  if [ $? -ne 0 ];then
    return $Err_MkEdgePkgPathFailed
  fi

  tar xzf ${AtlasEdgeTar} -C ${APP_PATH}/${EdgePkg}
  if [ $? -ne 0 ];then
    rm -rf ${APP_PATH}/${EdgePkg}
    return $Err_UnzpiEdgePkgFailed
  fi

  ${APP_PATH}/${EdgePkg}/${INSTALL} -install_dir ${APP_PATH} --ignore_docker_status_check
  if [ $? -ne 0 ];then
    rm -rf ${APP_PATH}/${EdgePkg}
    return $Err_InstallEdgeFailed
  fi

  cp ${APP_PATH}/AtlasEdge/software/edge_site/edge_manager/config/A500_capability.json ${APP_PATH}/AtlasEdge/software/edge_site/edge_manager/config/default_capability.json
  sed -i 's|"useSecuritySetting".*|"useSecuritySetting":true,|g' ${APP_PATH}/AtlasEdge/software/edge_core/conf/podconfig.json

  if [ ! -d "/home/data/" ];then
    mkdir -p /home/data && chmod 755 /home/data
    if [ $? -ne 0 ];then
    rm -rf ${APP_PATH}/${EdgePkg}
      return $Err_MkdirHomeDataFailed
    fi

    cp -rf ${APP_PATH}/AtlasEdge/software/cert_key/config /home/data/
    if [ $? -ne 0 ];then
      rm -rf ${APP_PATH}/${EdgePkg}
      return $Err_CpCertKeyFailed
    fi
  else
    # Atlas500 场景下已存在密钥材料，需要平滑
    cp -f /home/data/config/main/config/work/.baseMcsCert.enc /home/data/config/main/config/work/.default1.enc
    cp -f /home/data/config/main/config/work/.baseMcsCert.enc /home/data/config/bak/config/work/.default1.enc
    cp -f /home/data/config/main/config/work/.userMcsCert.enc /home/data/config/main/config/work/.default2.enc
    cp -f /home/data/config/main/config/work/.userMcsCert.enc /home/data/config/bak/config/work/.default2.enc
    cp -f /home/data/config/main/config/work/.ipc.enc /home/data/config/main/config/work/.default3.enc
    cp -f /home/data/config/main/config/work/.ipc.enc /home/data/config/bak/config/work/.default3.enc
  fi

  bash ${APP_PATH}/AtlasEdge/run.sh config  --install_type=Typical --ha_enable=1 --ha_work_path=${APP_PATH}/ha/
  if [ $? -ne 0 ];then
    rm -rf ${APP_PATH}/${EdgePkg}
    return $Err_CfgEdgeFailed
  fi

  # set no sys load mode
  bash ${APP_PATH}/AtlasEdge/run.sh config -no_sys_load_mode=1
  if [ $? -ne 0 ];then
    rm -rf ${APP_PATH}/${EdgePkg}
    return $Err_CfgEdgeFailed
  fi

  rm -rf ${APP_PATH}/${EdgePkg}
  return $Err_OK
}

function installHA()
{
  HAPkgPath="HAPacket"
  HAPkg=`ls|grep -E "ha|HA" |grep tar.gz$ `

  if [[ -z "${HAPkg}" ]]; then
    logger_Info "find No HAPkg return"
    return $Err_findNoAtlasEdgePacket
  fi

  mkdir -p ${APP_PATH}/${HAPkgPath}
  tar -xzf ${HAPkg} -C ${APP_PATH}/${HAPkgPath}
  if [ $? -ne 0 ];then
      rm -rf ${APP_PATH}/${HAPkgPath}
    return $Err_UnZipHA1Failed
  fi
  cd ${APP_PATH}/${HAPkgPath}
  ${APP_PATH}/${HAPkgPath}/${INSTALL} -p ${APP_PATH}
  if [ $? -ne 0 ];then
    cd -
    rm -rf ${APP_PATH}/${HAPkgPath}
    return $Err_InstallHAFailed
  fi   

  cd -
  rm -rf ${APP_PATH}/${HAPkgPath}
  return $Err_OK
}

function install_ascend_dmi_tool(){
    logger_Info "start install ascend dmi tool ..."
    ascend_dmi_run_path="ascend_dmi_tool_path"
    AscendDmiTar=`ls | grep "ascend_dmi_tool" | grep tar.gz$ `
    if [[ -z "${AscendDmiTar}" ]]; then
        logger_Info " No find ascend-dmi tar package"
        return ${Err_findNoAscendDmiTarPacket}
    fi
    mkdir -p ${ascend_dmi_run_path}
    tar_ret=`tar -zxf ${AscendDmiTar} -C ${ascend_dmi_run_path}`
    dmi_tool_file=`find ${ascend_dmi_run_path} -name "Ascend-dmi*.run"`
    if [[ ! -f ${dmi_tool_file} ]]; then
        logger_Info " No find ascend-dmi run package"
        return ${Err_findNoAscendDmiRunPacket}
    fi
    logger_Info " find ascend-dmi tool: ${dmi_tool_file}"
    chmod +x ${dmi_tool_file}
    mount -t ext4 ${P4} ${ascend_dmi_install_path}
    export TMPDIR=$(pwd)/${ascend_dmi_run_path}
    export USER=$(whoami)
    install_ret=`./${dmi_tool_file} --install --install-path=${ascend_dmi_install_path}`
    logger_Info "install ascend-dmi tool finish:  $install_ret"
    umount ${ascend_dmi_install_path}
    rm -rf ${ascend_dmi_run_path}
    return ${Err_OK}
}

function clearPkg()
{
  return 0
}

function keyManagerHandle()
{
    rm ${APP_PATH}/AtlasEdge/software/libs/libcrypto.so*
    if [ $? -ne 0 ];then
      return $Err_HandleKeyManagerError
    fi      

    rm ${APP_PATH}/AtlasEdge/software/libs/libssl.so*
    if [ $? -ne 0 ];then
      return $Err_HandleKeyManagerError
    fi  

    return $Err_OK  
}

copy_webfile_to_webworkdir(){

  EDGE_WORK_DIR=$1
  
  if [ ! -d ${EDGE_WORK_DIR}/AtlasEdge/software/edge_portal  ];then
    logger_Warn "web file not exit"
    return $Err_WebFileNotExist
  fi

  mkdir -p ${EDGE_WORK_DIR}/edge_portal
  cp -rf ${EDGE_WORK_DIR}/AtlasEdge/software/edge_portal/src ${EDGE_WORK_DIR}/edge_portal
  chown -R nobody:nobody ${EDGE_WORK_DIR}/edge_portal
  cp -rf ${EDGE_WORK_DIR}/AtlasEdge/software/edge_portal/alarm.xml/alarm_info_solution_en.xml /usr/local/nginx/html/manager/i18n/en-US/
  cp -rf ${EDGE_WORK_DIR}/AtlasEdge/software/edge_portal/alarm.xml/alarm_info_solution_cn.xml /usr/local/nginx/html/manager/i18n/zh-CN/
  chown nobody:nobody /usr/local/nginx/html/manager/i18n/en-US/alarm_info_solution_en.xml /usr/local/nginx/html/manager/i18n/zh-CN/alarm_info_solution_cn.xml
  chmod 400 /usr/local/nginx/html/manager/i18n/en-US/alarm_info_solution_en.xml /usr/local/nginx/html/manager/i18n/zh-CN/alarm_info_solution_cn.xml

  if [ -d /usr/local/nginx/html/manager/src/onlinehelp ]; then
    cp -rf ${EDGE_WORK_DIR}/AtlasEdge/software/edge_portal/help/en/*.html /usr/local/nginx/html/manager/src/onlinehelp/en/
    cp -rf ${EDGE_WORK_DIR}/AtlasEdge/software/edge_portal/help/zh/*.html /usr/local/nginx/html/manager/src/onlinehelp/zh/
    chown nobody:nobody /usr/local/nginx/html/manager/src/onlinehelp/en/*.html /usr/local/nginx/html/manager/src/onlinehelp/zh/*.html
    chmod 400 /usr/local/nginx/html/manager/src/onlinehelp/en/*.html /usr/local/nginx/html/manager/src/onlinehelp/zh/*.html
  fi

  return 0
}

function main()
{
    setEnv
    ret=$?
    if [ $ret -ne 0 ];then
      logger_Warn "set env failed:$ret"
      return $ret
    fi
    logger_Info "set env success:$ret"

    rmMiddleware

    installHA
    ret=$?
    if [ $ret -ne 0 ];then
      logger_Warn "install ha failed:$ret"
      return $ret
    fi
    logger_Info "install ha success:$ret"

    installAtlasEdge
    ret=$?
    if [ $ret -ne 0 ];then
      logger_Warn "install atlasedge failed:$ret"
      return $ret
    fi    
    logger_Info "install atlasedge success:$ret"

    install_ascend_dmi_tool

    keyManagerHandle
    if [ $ret -ne 0 ];then
      logger_Warn "key manager handle failed:$ret"
      return $ret
    fi   
    logger_Info "key manager handle success:$ret"

   copy_webfile_to_webworkdir ${APP_PATH}
   ret=$?
   if [ $ret -ne 0 ];then
      logger_Warn "webfile copy failed:$ret"
      return $ret
   fi
   logger_Info "webfile copy success:$ret"

    clearPkg
    return $Err_OK
}

main "$@"
RESULT=$?
exit $RESULT
